package com.zxtech.zzm.core.util

import android.content.Context
import android.content.SharedPreferences

class SharedprefsUtil {
  companion object {
    val ZXMONITOR_PREFERENCE = "ZXMONITOR_PREFERENCE"
    val ZXTABLET_PREFERENCE = "ZXTABLET_PREFERENCE"
    fun getSP(context: Context): SharedPreferences {
      return context.getSharedPreferences(ZXMONITOR_PREFERENCE, Context.MODE_PRIVATE)
    }

    fun clearData(context: Context){
      val sharedPreferences = context.getSharedPreferences(ZXMONITOR_PREFERENCE, Context.MODE_PRIVATE)
      val editor = sharedPreferences.edit()
      editor.clear()
      editor.apply()
    }

    fun saveData(
      context: Context,
      key: String?,
      data: Any
    ) {
      saveData(context, ZXMONITOR_PREFERENCE, key, data)
    }

    /**
     * 保存数据到文件
     */
    fun saveData(
      context: Context,
      filename: String?,
      key: String?,
      data: Any
    ) {
      val type = data.javaClass.simpleName
      val sharedPreferences = context.getSharedPreferences(filename, Context.MODE_PRIVATE)
      val editor = sharedPreferences.edit()
      when (type) {
        "Integer" -> {
          editor.putInt(key, (data as Int))
        }
        "Boolean" -> {
          editor.putBoolean(key, (data as Boolean))
        }
        "String" -> {
          editor.putString(key, data as String)
        }
        "Float" -> {
          editor.putFloat(key, (data as Float))
        }
        "Long" -> {
          editor.putLong(key, (data as Long))
        }
      }
      editor.apply()
    }

    /*fun getData(
      key: String?,
      defValue: Any
    ): Any? {
      return getData(ZXMonitorApplication.getContext(), key, defValue)
    }*/

    fun getData(
      context: Context,
      key: String?,
      defValue: Any
    ): Any? {
      return getData(context, ZXMONITOR_PREFERENCE, key, defValue)
    }

    /**
     * 从文件中读取数据
     */
    fun getData(
      context: Context,
      filename: String?,
      key: String?,
      defValue: Any
    ): Any? {
      val type = defValue.javaClass.simpleName
      val sharedPreferences = context.getSharedPreferences(filename, Context.MODE_PRIVATE)
      //defValue为为默认值，如果当前获取不到数据就返回它
      when (type) {
        "Integer" -> {
          return sharedPreferences.getInt(key, (defValue as Int))
        }
        "Boolean" -> {
          return sharedPreferences.getBoolean(key, (defValue as Boolean))
        }
        "String" -> {
          return sharedPreferences.getString(key, defValue as String)
        }
        "Float" -> {
          return sharedPreferences.getFloat(key, (defValue as Float))
        }
        "Long" -> {
          return sharedPreferences.getLong(key, (defValue as Long))
        }
        else -> return null
      }
    }
  }
}